package com.chen.proxy.cglib;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
 * 使用cglib产生代理类， 委托类不必实现接口
 *  	cglib 需要asm.jar
 * 2015-8-27 15:09:58
 * @author jinlong.chen
 */
public class CglibProxy implements MethodInterceptor {
	private Object targetObject = null;
	
	public Object createPoxyInstrance(Object object) {
		this.targetObject = object;
		
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(this.targetObject.getClass());
		enhancer.setCallback(this);
		enhancer.setClassLoader(object.getClass().getClassLoader());
		
		return enhancer.create();
	}
	
	@Override
	public Object intercept(Object proxy,Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {		
		System.out.println("委托类："+proxy.getClass().getName()+"  ,  方法："+method.getName());
		System.out.println("  Proxy class : "+this.getClass().getName()+"  , hashCode : "+this.hashCode());
		
		/**
		 * doSth
		 */
		Object returnValue = method.invoke(targetObject,objects);
		
		return returnValue;
	}
}